package com.eliza.net.activity

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.eliza.net.R
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException


class OkHttpActivity : AppCompatActivity() {
    private lateinit var etv: EditText
    private val url =
        "https://www.baidu.com/home/other/data/weatherInfo?city=%E6%AD%A6%E6%B1%89&indextype=manht&_req_seqid=0xfc7ab7ff0008878d&asyn=1&t=1588658358650&sid=1421_31125_21122_31426_31342_31270_31464_31228_30823_26350_31164"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ok_http)

        etv = findViewById<EditText>(R.id.et_res);

        findViewById<Button>(R.id.btn_get).setOnClickListener {
            getReq()
        }
        findViewById<Button>(R.id.btn_post).setOnClickListener {
            getReq()
        }

    }


    fun getReq() {
        //第一步获取okHttpClient对象
        //第二步构建Request对象
        //第三步构建Call对象
        val call: Call = OkHttpClient.Builder().build()
            .newCall(
                Request.Builder()
                    .url(url)
                    .get()
                    .build()
            )
        //第四步:异步get请求//  fun enqueue(responseCallback: Callback)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e(this::class.java.name, "==>getReq -- onFailure::${e.message}");
            }

            override fun onResponse(call: Call, response: Response) {
                Log.e(this::class.java.name, "==>getReq--onResponse");
                //得到的子线程
                response.body?.let {
//                    fun setText(text: CharArray?, start: Int, len: Int) { /* compiled code */
                    etv.setText(it.string())
                }
            }
        })
    }

    fun postResp() {


        var jsonStr = JSONObject(
            HashMap<String, String>().apply {
                this.put("name", "法外狂徒")
                this.put("age", "123")
            } as Map<String, String>).toString()


        //第二步创建RequestBody（Form 表单形式）
//        RequestBody body = new FormBody.Builder()
//                .add("mobile", "demoData")
//                .add("password", "demoData")
//                .build();
/*
older method:
     val requestBodyJson: RequestBody = RequestBody.create(
                "application/json;charset=utf-8".toMediaTypeOrNull(), jsonStr
            )
 */

        var requestBodyJson = jsonStr.toRequestBody("application/json;charset=utf-8".toMediaType())

        //第一步创建OKHttpClient
        val newCall = OkHttpClient.Builder()
            .build().newCall(
                Request.Builder()
                    .url("http://192.168.31.32:8080/renren-fast/app/login")
                    .addHeader("contentType", "application/json;charset=UTF-8")
                    .post(requestBodyJson)
                    .build()
            )

        newCall.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e(this::class.java.name, "==>postResp -- onFailure::${e.message}");
            }

            override fun onResponse(call: Call, response: Response) {
                Log.e(this::class.java.name, "==>postResp--onResponse");
                //得到的子线程
                response.body?.let {
//                    fun setText(text: CharArray?, start: Int, len: Int) { /* compiled code */
                    etv.setText(it.string())
                }
            }
        })

    }
}